var app = getApp()
var locat = require('../../utils/Location.js');
var util = require('../../utils/util.js');
var status = require('../../utils/index.js');
var wcache = require('../../utils/wcache.js');

Page({
    mixins: [require('../../mixin/globalMixin.js')],
    data: {
        currentIndex: 0, //默认是活动项
        payBtnLoading: false,
        show: false,
        showConfirmModal: false,
        receiverAddress: "", //快递送货地址
        tuan_send_address: "", //团长送货地址
        showGetPhone: false,
        lou_meng_hao: '',
        pickUpAddress: "",
        disUserName: "",
        pickUpCommunityName: "",
        is_limit_distance_buy: 0,
        tabList: [
            { id: 0, name: '社区自提', dispatching: 'pickup', enabled: false },
            { id: 1, name: '团长配送', dispatching: 'tuanz_send', enabled: false },
            { id: 2, name: '快递配送', dispatching: 'express', enabled: false },
            { id: 3, name: '同城配送', dispatching: 'localtown_delivery', enabled: false },
            { id: 4, name: '到店核销', dispatching: 'hexiao', enabled: false }
        ],
        originTabList: [
            { id: 0, name: '社区自提', dispatching: 'pickup' },
            { id: 1, name: '团长配送', dispatching: 'tuanz_send' },
            { id: 2, name: '快递配送', dispatching: 'express' },
            { id: 3, name: '同城配送', dispatching: 'localtown_delivery' },
            { id: 4, name: '到店核销', dispatching: 'hexiao' }
        ],
        tabIdx: 0,
        region: ['选择地址', '', ''],
        tot_price: 0,
        needAuth: false,
        reduce_money: 0,
        hide_quan: true,
        tuan_region: ['选择地址', '', ''],
        groupInfo: {
            group_name: '社区',
            owner_name: '团长',
            placeorder_tuan_name: '配送费',
            placeorder_trans_name: '快递费'
        },
        comment: '',
        is_yue_open: 0,
        can_yupay: 0,
        ck_yupay: 0,
        use_score: 0,
        commentArr: {},
        note_content: '',
        showAlertTime: false,
        curAlertTime: -1,
        isAgreePresale: false,
        presale_info: '',
        presalePickup: ['自提', '配送', '发货', '配送', '核销'],
        allform: ""
    },
    canPay: true,
    canPreSub: true,
    // 切换swiper-item触发bindchange事件
    pagechange: function (e) {
        // 通过touch判断，改变tab的下标值
        if ("touch" === e.detail.source) {
            let currentPageIndex = this.data.currentIndex;
            currentPageIndex = (currentPageIndex + 1) % 2;
            // 拿到当前索引并动态改变
            this.setData({
                currentIndex: currentPageIndex,
            })
        }
    },
    handleOpenNo() {
        this.setData({
            show: false
        });
    },
    erweima() {
        this.setData({
            show: true
        })
    },

    //点击tab时触发
    titleClick: function (e) {
        this.setData({
            //拿到当前索引并动态改变
            currentIndex: e.currentTarget.dataset.idx
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this;
        status.setGroupInfo().then((groupInfo) => { that.setData({ groupInfo }) });
        var token = wx.getStorageSync('token');
        var community = wx.getStorageSync('community');
        var community_id = community.communityId;
        // let is_limit = options.is_limit || 0;
        app.util.request({
            url: 'entry/wxapp/user',
            data: {
                controller: 'car.checkout',
                token: token,
                community_id,
                buy_type: options.type,
            },
            dataType: 'json',
            method: 'POST',
            success: function (res) {
                // wx.hideLoading();
                setTimeout(function () { wx.hideLoading(); }, 1000);

                let rdata = res.data;
                // 提货方式
                let tabIdx = -1;
                let tabLength = 0;
                let tabList = that.data.tabList || {};
                let sortTabList = [];

                let {
                    delivery_express_name,
                    delivery_tuanzshipping_name,
                    delivery_ziti_name,
                    delivery_diy_sort,
                    delivery_type_express,
                    delivery_type_tuanz,
                    delivery_type_ziti,
                    delivery_tuanz_money,
                    is_vip_card_member,
                    vipcard_save_money,
                    level_save_money,
                    is_open_vipcard_buy,
                    is_member_level_buy,
                    total_integral,
                    is_need_subscript,
                    need_subscript_template,
                    delvery_type_hexiao,
                    order_note_open,
                    order_note_name,
                    order_note_content,
                    delivery_type_localtown,
                    localtown_dispatchtime, //预计配送需要多少分钟
                    pickingup_fare, //订单包装费，只有在 同城快递的时
                    localtown_shipping_fare, //同城配送费
                    localtown_modifypickingname,
                    localtown_shipping_fare_arr,
                    localtown_moneytype_fixed_freemoney,
                    localtown_makeup_delivery_money,
                    localtown_expected_delivery,
                    order_lou_meng_hao,
                    order_lou_meng_hao_placeholder,
                    presale_info,
                    cashondelivery_data,
                    allform
                } = res.data;

                let {
                    isopen_cashondelivery,
                    isopen_cashondelivery_communityhead,
                    isopen_cashondelivery_express,
                    isopen_cashondelivery_hexiao,
                    isopen_cashondelivery_localtown
                } = cashondelivery_data;
                // 同城配送TODO...
                sortTabList.push({ id: 3, name: '同城配送', dispatching: 'localtown_delivery', enabled: (delivery_type_localtown == 1) });
                if (tabIdx == -1 && delivery_type_localtown == 1) tabIdx = 3;
                let localtown_delivery_space_month = '';
                if (localtown_expected_delivery && localtown_expected_delivery.localtown_delivery_space_month) {
                    localtown_delivery_space_month = localtown_expected_delivery.localtown_delivery_space_month;
                }


                var addres = 0;
                addres = 1;
                var seller_chose_id = 0;
                var seller_chose_store_id = 0;
                var seller_goods = rdata.seller_goodss;

                let commentArr = {};
                for (let key in seller_goods) commentArr[key] = '';

                let sel_chose_vouche = '';
                let sgvKey = 0;
                let goodsTotNum = 0;
                for (var i in seller_goods) {
                    if (seller_goods[i].show_voucher == 1) {
                        if (seller_goods[i].chose_vouche.id) seller_chose_id = seller_goods[i].chose_vouche.id;
                        if (seller_goods[i].chose_vouche.store_id) seller_chose_store_id = seller_goods[i].chose_vouche.store_id;

                        if (Object.prototype.toString.call(seller_goods[i].chose_vouche) == '[object Object]') {
                            sel_chose_vouche = seller_goods[i].chose_vouche;
                        }
                        if (Object.keys(seller_goods[i].chose_vouche).length > 0) sgvKey = i;
                    }
                    seller_goods[i].goodsnum = Object.keys(seller_goods[i].goods).length;
                    for (var j in seller_goods[i].goods) {
                        goodsTotNum += seller_goods[i].goods[j].quantity * 1;
                        if (seller_goods[i].goods[j].header_disc > 0 && seller_goods[i].goods[j].header_disc < 100) {
                            seller_goods[i].goods[j].header_disc = (seller_goods[i].goods[j].header_disc / 10).toFixed(1);
                        }
                    }
                }

                let current_distance = rdata.current_distance || '';
                let current_distance_str = that.changeDistance(current_distance);

                order_note_content = order_note_content != null ? order_note_content : '';

                if (presale_info && presale_info.goods_price) {
                    let deduction_money = presale_info.deduction_money;
                    deduction_money = deduction_money > 0 ? deduction_money : presale_info.presale_ding_money;
                    let totDeduction = deduction_money * goodsTotNum;
                    presale_info.balance = (presale_info.goods_price * 1 - totDeduction).toFixed(2);
                    presale_info.totdingMoney = (goodsTotNum * presale_info.presale_ding_money).toFixed(2);
                    presale_info.totDeduction = totDeduction.toFixed(2);
                }

                let param = {
                    sgvKey,
                    is_hexiao: delvery_type_hexiao,
                    loadover: true,
                    commentArr,
                    sel_chose_vouche,
                    tabList: sortTabList,
                    is_limit_distance_buy: rdata.is_limit_distance_buy || 0,
                    tabIdx: tabIdx,
                    tabLength: tabLength,
                    tuan_send_address: rdata.tuan_send_address,
                    is_open_order_message: rdata.is_open_order_message,
                    is_yue_open: rdata.is_yue_open,
                    can_yupay: rdata.can_yupay,
                    show_voucher: rdata.show_voucher,
                    current_distance,
                    man_free_tuanzshipping: rdata.man_free_tuanzshipping * 1 || 0,
                    man_free_shipping: rdata.man_free_shipping * 1 || 0,
                    index_hide_headdetail_address: rdata.index_hide_headdetail_address || 0,
                    open_score_buy_score: rdata.open_score_buy_score || 0,
                    score: rdata.score || 0,
                    score_for_money: rdata.score_for_money || 0,
                    bue_use_score: rdata.bue_use_score || 0,
                    is_man_delivery_tuanz_fare: rdata.is_man_delivery_tuanz_fare,   //是否达到满xx减团长配送费
                    fare_man_delivery_tuanz_fare_money: rdata.fare_man_delivery_tuanz_fare_money,   //达到满xx减团长配送费， 减了多少钱
                    is_man_shipping_fare: rdata.is_man_shipping_fare,    //是否达到满xx减运费
                    fare_man_shipping_fare_money: rdata.fare_man_shipping_fare_money,   //达到满xx减运费，司机减了多少运费
                    is_vip_card_member,
                    vipcard_save_money,
                    level_save_money,
                    is_open_vipcard_buy,
                    is_member_level_buy,
                    // canLevelBuy,
                    total_integral: total_integral || '',
                    is_need_subscript,
                    need_subscript_template,
                    current_distance_str,
                    order_note_open,
                    order_note_name,
                    order_note_content,
                    note_content: order_note_content,
                    localtown_dispatchtime,
                    pickingup_fare,
                    localtown_shipping_fare,
                    localtown_modifypickingname: localtown_modifypickingname || '包装费',
                    localtown_shipping_fare_arr,
                    localtown_moneytype_fixed_freemoney,
                    localtown_makeup_delivery_money,
                    localtown_expected_delivery,
                    localtown_delivery_space_month,
                    order_lou_meng_hao: order_lou_meng_hao || '楼号门牌',
                    order_lou_meng_hao_placeholder: order_lou_meng_hao_placeholder || '例如:A座106室',
                    presale_info,
                    cashondelivery_data,
                    allform
                }

                let addrObj = rdata.address || {};
                let tuan_send_address_info = rdata.tuan_send_address_info || {};
                let tuanAddress = tuan_send_address_info.address || '选择位置';
                if (tuan_send_address_info.city_name == "" || tuan_send_address_info.city_id == 3708 || tuan_send_address_info.country_name == "" || tuan_send_address_info.country_id == 3708) {
                    tuanAddress = '选择位置';
                }

                // 20200710 TODO
                // addrObj = tuan_send_address_info;

                param.tabAddress = [
                    {
                        name: rdata.ziti_name || '',
                        mobile: rdata.ziti_mobile || ''
                    },
                    {
                        name: tuan_send_address_info.name || '',
                        mobile: tuan_send_address_info.telephone || '',
                        receiverAddress: tuanAddress,
                        lou_meng_hao: tuan_send_address_info.lou_meng_hao || '',
                        region: [tuan_send_address_info.province_name || "", tuan_send_address_info.city_name || "", tuan_send_address_info.country_name || ""]
                    },
                    {
                        name: addrObj.name || '',
                        mobile: addrObj.telephone || '',
                        receiverAddress: addrObj.address || '',
                        region: [addrObj.province_name || "选择地址", addrObj.city_name || "", addrObj.country_name || ""]
                    },
                    {
                        name: addrObj.name || '',
                        mobile: addrObj.telephone || '',
                        receiverAddress: addrObj.address || '',
                        region: [addrObj.province_name || "选择地址", addrObj.city_name || "", addrObj.country_name || ""]
                    },
                    {
                        name: rdata.ziti_name || '',
                        mobile: rdata.ziti_mobile || ''
                    }
                ];

                if (JSON.stringify(addrObj) != '[]') {
                    if (addrObj.lon_lat == '') {
                        if (tabIdx == 3) {
                            param.tabAddress[3] = {
                                name: addrObj.name || '',
                                mobile: addrObj.telephone || '',
                                receiverAddress: '',
                                region: ["选择地址", "", ""]
                            }
                        }
                    } else if (addrObj.lon_lat) {
                        let lat_lon = addrObj.lon_lat.split(',');
                        wcache.put('latitude2', lat_lon[1]);
                        wcache.put('longitude2', lat_lon[0]);
                    }
                }

                if (addres == 1) {
                    that.setData({
                        ...param,
                        pick_up_time: res.data.pick_up_time,
                        pick_up_type: res.data.pick_up_type,
                        pick_up_weekday: res.data.pick_up_weekday,
                        addressState: true,
                        is_integer: res.data.is_integer,
                        is_ziti: res.data.is_ziti,
                        pick_up_arr: res.data.pick_up_arr,
                        seller_goodss: res.data.seller_goodss,
                        seller_chose_id: seller_chose_id,
                        seller_chose_store_id: seller_chose_store_id,
                        goods: res.data.goods,
                        buy_type: res.data.buy_type,
                        yupay: res.data.can_yupay,
                        is_yue_open: res.data.is_yue_open,
                        yu_money: res.data.yu_money,
                        total_free: res.data.total_free,
                        trans_free_toal: res.data.trans_free_toal,
                        delivery_tuanz_money: res.data.delivery_tuanz_money,
                        reduce_money: res.data.reduce_money,
                        is_open_fullreduction: res.data.is_open_fullreduction,
                        cha_reduce_money: res.data.cha_reduce_money
                    }, () => {
                        that.calcPrice();
                    })
                } else {
                    that.setData({
                        ...param,
                        is_integer: res.data.is_integer,
                        addressState: false,
                        goods: res.data.goods,
                        is_ziti: res.data.is_ziti,
                        pick_up_arr: res.data.pick_up_arr,
                        seller_goodss: res.data.seller_goodss,
                        seller_chose_id: seller_chose_id,
                        seller_chose_store_id: seller_chose_store_id,
                        buy_type: res.data.buy_type,
                        yupay: res.data.can_yupay,
                        is_yue_open: res.data.is_yue_open,
                        yu_money: res.data.yu_money,
                        total_free: res.data.total_free,
                        trans_free_toal: res.data.trans_free_toal,
                        delivery_tuanz_money: res.data.delivery_tuanz_money,
                        reduce_money: res.data.reduce_money,
                        is_open_fullreduction: res.data.is_open_fullreduction,
                        cha_reduce_money: res.data.cha_reduce_money
                    }, () => {
                        that.calcPrice();
                    })
                }

            }
        })
    },

    changeDistance: function (current_distance) {
        if (current_distance) {
            current_distance = parseFloat(current_distance);
            if (current_distance > 1000) {
                let current_distance_int = current_distance / 1000;
                return current_distance_int.toFixed(2) + 'km';
            }
            return current_distance + 'm';
        }
        return current_distance;
    },
})